using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using SmartMedicalRAG.Core.Models;
using System.Net.Http.Json;

namespace SmartMedicalRAG.Infrastructure.SemanticKernel;

/// <summary>
/// Semantic Kernel服务
/// </summary>
public class SemanticKernelService
{
    private readonly Kernel _kernel;
    private readonly IChatCompletionService _chatService;
    private readonly ILogger<SemanticKernelService> _logger;

    public SemanticKernelService(IConfiguration configuration, ILogger<SemanticKernelService> logger)
    {
        _logger = logger;
        
        var builder = Kernel.CreateBuilder();
        
        // 配置Ollama连接
        var endpoint = configuration["Ollama:Endpoint"] ?? "http://127.0.0.1:11434";
        var modelId = configuration["Ollama:ModelId"] ?? "deepseek-r1:8b";
        
        builder.Services.AddScoped<HttpClient>();
        builder.Services.AddScoped<SearchSkill>();
        
        // 使用HTTP客户端直接调用Ollama API
        // 注意：这里使用简化的实现，实际项目中应该使用专门的Ollama客户端
        
        _kernel = builder.Build();
        // 由于我们直接使用HTTP客户端，不需要chatService
        _chatService = null!;
        
        _logger.LogInformation("Semantic Kernel服务初始化完成，模型: {ModelId}, 端点: {Endpoint}", modelId, endpoint);
    }

    /// <summary>
    /// 生成回复
    /// </summary>
    /// <param name="prompt">提示</param>
    /// <param name="context">上下文</param>
    /// <returns>生成的回复</returns>
    public async Task<string> GenerateResponseAsync(string prompt, List<string>? context = null)
    {
        try
        {
            var httpClient = _kernel.GetRequiredService<HttpClient>();
            var endpoint = "http://127.0.0.1:11434";
            var modelId = "deepseek-r1:8b";
            
            // 构建完整的提示
            var fullPrompt = "你是一个专业的医疗分诊助手，基于检索到的医学知识为患者提供准确的分诊建议。\n\n";
            
            if (context != null && context.Any())
            {
                fullPrompt += $"基于以下医学知识:\n{string.Join("\n", context)}\n\n";
            }
            
            fullPrompt += $"患者描述: {prompt}\n\n请提供分诊建议:";
            
            // 调用Ollama API
            var request = new
            {
                model = modelId,
                prompt = fullPrompt,
                stream = false
            };
            
            var response = await httpClient.PostAsJsonAsync($"{endpoint}/api/generate", request);
            response.EnsureSuccessStatusCode();
            
            var result = await response.Content.ReadFromJsonAsync<OllamaResponse>();
            var assistantMessage = result?.response ?? "抱歉，无法生成回复。";
            
            _logger.LogInformation("LLM回复生成完成，长度: {Length}", assistantMessage.Length);
            
            return assistantMessage;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成LLM回复失败");
            return "抱歉，生成回复时出现错误。";
        }
    }

    /// <summary>
    /// 搜索知识
    /// </summary>
    /// <param name="query">查询</param>
    /// <returns>搜索结果</returns>
    public async Task<SearchResult> SearchKnowledgeAsync(string query)
    {
        try
        {
            var searchSkill = _kernel.GetRequiredService<SearchSkill>();
            var result = await searchSkill.SearchAsync(query);
            
            var searchResult = new SearchResult
            {
                Query = query,
                Results = result.ToList(),
                Timestamp = DateTime.UtcNow
            };
            
            _logger.LogInformation("知识搜索完成，查询: {Query}, 结果数量: {ResultCount}", query, result.Count());
            
            return searchResult;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "知识搜索失败");
            throw;
        }
    }
}

/// <summary>
/// Ollama API响应
/// </summary>
public class OllamaResponse
{
    public string model { get; set; } = string.Empty;
    public string response { get; set; } = string.Empty;
    public bool done { get; set; }
}

/// <summary>
/// 搜索技能
/// </summary>
public class SearchSkill
{
    private readonly ILogger<SearchSkill> _logger;

    public SearchSkill(ILogger<SearchSkill> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 搜索
    /// </summary>
    /// <param name="query">查询</param>
    /// <returns>搜索结果</returns>
    public async Task<IEnumerable<object>> SearchAsync(string query)
    {
        // 这里应该实现实际的搜索逻辑
        // 简化实现，返回模拟结果
        _logger.LogInformation("执行搜索查询: {Query}", query);
        
        await Task.Delay(100); // 模拟搜索延迟
        
        return new List<object>
        {
            new { Title = "医学指南1", Content = "相关医学知识内容1" },
            new { Title = "医学指南2", Content = "相关医学知识内容2" },
            new { Title = "相似病例", Content = "相似病例信息" }
        };
    }
} 